package pl.edu.pk.rz.validator;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import pl.edu.pk.rz.command.LoginCommand;

@Component
public class UserValidator implements Validator {

	protected Logger logger = Logger.getLogger(this.getClass());

	public void validate(Object object, Errors errors) {
		logger.info("Validating login credentials");
		LoginCommand command = (LoginCommand) object;

		if (!StringUtils.isAlphanumericSpace(command.getUsername())) {
			errors.rejectValue(LoginCommand.FIELD_USERNAME, "validation.generalError");
		}
		if (StringUtils.isWhitespace(command.getUsername())) {
			errors.rejectValue(LoginCommand.FIELD_USERNAME, "validation.fieldRequired");
		}
		if (command.getUsername().length()<3 || command.getUsername().length()>15) {
			errors.rejectValue(LoginCommand.FIELD_USERNAME, "validation.lengthNotValid");
		}

	}

	public boolean supports(Class<?> clazz) {
		return LoginCommand.class.isAssignableFrom(clazz);
	}
}
